// 作业管理页面
import React, { useState, useEffect, useRef } from 'react';
import { Layout, Card, Form, Input, Select, Radio, Button, Table, message, Space, Typography, Tag, Progress, Collapse, Modal, Statistic, Row, Col, Divider } from 'antd';
import { PlusOutlined, PlayCircleOutlined, StopOutlined, ReloadOutlined, BarChartOutlined } from '@ant-design/icons';
import { mockService } from '../services/mockService';
import type { FeatureView, Job } from '../types';
import { formatDateTime } from '../utils/fileUtils';
import * as echarts from 'echarts';

const { Content } = Layout;
const { Text, Title } = Typography;
const { Option } = Select;
const { Panel } = Collapse;

const JobsPage: React.FC = () => {
  const [featureViews, setFeatureViews] = useState<FeatureView[]>([]);
  const [jobs, setJobs] = useState<Job[]>([]);
  const [selectedFeatureView, setSelectedFeatureView] = useState<string>('');
  const [jobForm] = Form.useForm();
  const [modelForm] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [expandedJobId, setExpandedJobId] = useState<string | null>(null);
  const [showResultsModal, setShowResultsModal] = useState(false);
  const [currentJob, setCurrentJob] = useState<Job | null>(null);
  const [showSaveModelModal, setShowSaveModelModal] = useState(false);
  const chartRef = useRef<HTMLDivElement>(null);
  const chartInstance = useRef<echarts.ECharts | null>(null);
  const [modelTemplates] = useState([
    {
      id: 'random_forest',
      name: '随机森林',
      description: '适用于分类和回归任务的集成学习算法',
      hyperparameters: {
        n_estimators: { type: 'number', label: '树的数量', default: 100, min: 10, max: 500 },
        max_depth: { type: 'number', label: '最大深度', default: 10, min: 1, max: 50 },
        min_samples_split: { type: 'number', label: '最小分裂样本数', default: 2, min: 2, max: 20 }
      }
    },
    {
      id: 'xgboost',
      name: 'XGBoost',
      description: '高效的梯度提升框架',
      hyperparameters: {
        learning_rate: { type: 'number', label: '学习率', default: 0.1, min: 0.01, max: 1, step: 0.01 },
        max_depth: { type: 'number', label: '最大深度', default: 8, min: 1, max: 30 },
        n_estimators: { type: 'number', label: '估计器数量', default: 200, min: 10, max: 1000 }
      }
    },
    {
      id: 'logistic_regression',
      name: '逻辑回归',
      description: '用于二分类问题的线性模型',
      hyperparameters: {
        C: { type: 'number', label: '正则化强度', default: 1.0, min: 0.01, max: 10, step: 0.1 },
        max_iter: { type: 'number', label: '最大迭代次数', default: 100, min: 10, max: 1000 }
      }
    }
  ]);

  // 加载数据
  useEffect(() => {
    loadInitialData();
    // 定期刷新作业状态
    const interval = setInterval(loadJobs, 5000);
    return () => clearInterval(interval);
  }, []);

  const loadInitialData = async () => {
    try {
      setLoading(true);
      // 加载特征视图
      const featureViewsRes = await mockService.featureViews.getAll();
      if (featureViewsRes.success && featureViewsRes.data) {
        setFeatureViews(featureViewsRes.data);
        if (featureViewsRes.data.length > 0) {
          setSelectedFeatureView(featureViewsRes.data[0].id);
        }
      }
      // 加载作业
      await loadJobs();
    } catch (error) {
      message.error('数据加载失败');
      console.error('加载错误:', error);
    } finally {
      setLoading(false);
    }
  };

  const loadJobs = async () => {
    try {
      const jobsRes = await mockService.jobs.getAll();
      if (jobsRes.success && jobsRes.data) {
        setJobs(jobsRes.data);
      }
    } catch (error) {
      console.error('加载作业失败:', error);
    }
  };

  // 处理作业创建
  const handleJobSubmit = async (values: any) => {
    try {
      setLoading(true);
      
      const selectedTemplate = modelTemplates.find(t => t.id === values.templateId);
      if (!selectedTemplate) {
        message.error('请选择有效的模型模板');
        return;
      }

      // 构建超参数字典
      const hyperparameters: Record<string, any> = {};
      Object.entries(selectedTemplate.hyperparameters).forEach(([key, param]) => {
        hyperparameters[key] = values[key] !== undefined ? values[key] : param.default;
      });

      const jobData: Omit<Job, 'id' | 'status' | 'createdAt' | 'updatedAt'> = {
        name: values.name,
        type: values.type,
        featureViewId: selectedFeatureView,
        modelConfig: {
          templateId: values.templateId,
          modelType: selectedTemplate.name,
          hyperparameters
        }
      };

      const response = await mockService.jobs.create(jobData);
      
      if (response.success && response.data) {
        setJobs(prev => [response.data as Job, ...prev]);
        message.success('作业创建成功！');
        jobForm.resetFields(['name']); // 重置部分表单
      } else {
        message.error(response.error || '作业创建失败');
      }
    } catch (error) {
      message.error('作业创建失败，请重试');
      console.error('错误:', error);
    } finally {
      setLoading(false);
    }
  };

  // 获取状态标签颜色
  const getStatusColor = (status: Job['status']) => {
    switch (status) {
      case 'pending':
        return 'default';
      case 'running':
        return 'processing';
      case 'completed':
        return 'success';
      case 'failed':
        return 'error';
      default:
        return 'default';
    }
  };

  // 获取状态文本
  const getStatusText = (status: Job['status']) => {
    switch (status) {
      case 'pending':
        return '等待中';
      case 'running':
        return '运行中';
      case 'completed':
        return '已完成';
      case 'failed':
        return '失败';
      default:
        return status;
    }
  };

  // 渲染模型模板配置
  const renderTemplateConfig = (templateId: string) => {
    const template = modelTemplates.find(t => t.id === templateId);
    if (!template) return null;

    return (
      <Card title={template.description} size="small">
        {Object.entries(template.hyperparameters).map(([key, param]) => (
          <Form.Item key={key} label={param.label} name={key} initialValue={param.default}>
            <Input
              type={param.type}
              min={param.min}
              max={param.max}
              step={param.step || 1}
              placeholder={`请输入${param.label}`}
            />
          </Form.Item>
        ))}
      </Card>
    );
  };

  // 渲染作业详情面板
  const renderJobDetails = (job: Job) => {
    const featureView = featureViews.find(fv => fv.id === job.featureViewId);

    return (
      <Collapse
        activeKey={expandedJobId === job.id ? ['details'] : []}
        onChange={() => setExpandedJobId(expandedJobId === job.id ? null : job.id)}
      >
        <Panel header="作业详情" key="details">
          <Space direction="vertical" style={{ width: '100%' }}>
            <div>
              <Text strong>特征视图：</Text>
              <Text>{featureView?.name || '-'}</Text>
            </div>
            <div>
              <Text strong>模型类型：</Text>
              <Text>{job.modelConfig.modelType}</Text>
            </div>
            <div>
              <Text strong>超参数配置：</Text>
              <pre style={{ background: '#f5f5f5', padding: '12px', borderRadius: '4px', overflow: 'auto' }}>
                {JSON.stringify(job.modelConfig.hyperparameters, null, 2)}
              </pre>
            </div>
            {job.metrics && (
              <div>
                <Text strong>评估指标：</Text>
                <Space wrap>
                  {Object.entries(job.metrics).map(([key, value]) => (
                    <Tag key={key} color="blue">
                      {key}: {value?.toFixed(4)}
                    </Tag>
                  ))}
                </Space>
                <Button 
                  type="primary" 
                  size="small" 
                  icon={<BarChartOutlined />} 
                  style={{ marginTop: '10px' }}
                  onClick={() => showJobResults(job)}
                >
                  查看详细结果
                </Button>
              </div>
            )}
          </Space>
        </Panel>
      </Collapse>
    );
  };

  // 显示作业结果
  const showJobResults = (job: Job) => {
    setCurrentJob(job);
    setShowResultsModal(true);
  };

  // 初始化结果图表
  useEffect(() => {
    if (showResultsModal && currentJob && chartRef.current && !chartInstance.current) {
      chartInstance.current = echarts.init(chartRef.current);
    }
    return () => {
      if (chartInstance.current) {
        chartInstance.current.dispose();
        chartInstance.current = null;
      }
    };
  }, [showResultsModal]);

  // 更新结果图表
  useEffect(() => {
    if (chartInstance.current && currentJob && currentJob.metrics) {
      const metrics = Object.entries(currentJob.metrics);
      
      const option = {
        title: {
          text: '模型性能指标',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [
          {
            name: '评估指标',
            type: 'pie',
            radius: '50%',
            data: metrics.map(([key, value]) => ({ value, name: key })),
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };
      
      chartInstance.current.setOption(option);
    }
  }, [currentJob, showResultsModal]);

  // 处理保存模型
  const handleSaveModel = async (values: any) => {
    if (!currentJob) return;
    
    try {
      setLoading(true);
      
      const modelData = {
        name: values.name,
        version: parseInt(values.version),
        description: values.description,
        jobId: currentJob.id,
        metrics: currentJob.metrics || {},
        config: currentJob.modelConfig
      };

      // 检查是否已存在相同名称和版本的模型
      const existingModels = await mockService.models.getAll();
      if (existingModels.success && existingModels.data) {
        const duplicate = existingModels.data.find(
          model => model.name === values.name && model.version === parseInt(values.version)
        );
        
        if (duplicate) {
          message.error('已存在相同名称和版本的模型，请修改版本号');
          return;
        }
      }

      const response = await mockService.models.save(modelData);
      
      if (response.success && response.data) {
        message.success('模型保存成功！');
        setShowSaveModelModal(false);
        setShowResultsModal(false);
        modelForm.resetFields();
      } else {
        message.error(response.error || '模型保存失败');
      }
    } catch (error) {
      message.error('模型保存失败，请重试');
      console.error('错误:', error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <Layout className="layout">
      <Content style={{ padding: '24px', minHeight: 'calc(100vh - 64px)' }}>
        <Card title="创建作业" extra={<Button type="primary" icon={<PlusOutlined />}>新建作业</Button>}>
          <Form
            form={jobForm}
            layout="vertical"
            onFinish={handleJobSubmit}
            style={{ maxWidth: '100%' }}
          >
            <Space direction="vertical" style={{ width: '100%' }}>
              <div style={{ display: 'flex', gap: '16px' }}>
                <Form.Item name="featureViewId" label="选择特征视图" style={{ flex: 1 }}>
                  <Select
                    value={selectedFeatureView}
                    onChange={(value) => setSelectedFeatureView(value)}
                    placeholder="请选择特征视图"
                    disabled={featureViews.length === 0}
                  >
                    {featureViews.map(fv => (
                      <Option key={fv.id} value={fv.id}>{fv.name}</Option>
                    ))}
                  </Select>
                </Form.Item>
                
                <Form.Item name="type" label="作业类型" style={{ flex: 1 }}>
                  <Radio.Group>
                    <Radio value="training">训练作业</Radio>
                    <Radio value="evaluation">评估作业</Radio>
                  </Radio.Group>
                </Form.Item>
              </div>

              <Form.Item name="name" label="作业名称" rules={[{ required: true, message: '请输入作业名称' }]}>
                <Input placeholder="请输入作业名称" />
              </Form.Item>

              <Form.Item name="templateId" label="选择模型模板" rules={[{ required: true, message: '请选择模型模板' }]}>
                <Select
                  placeholder="请选择模型模板"
                  onChange={(value) => jobForm.setFieldsValue({ templateId: value })}
                >
                  {modelTemplates.map(template => (
                    <Option key={template.id} value={template.id}>{template.name}</Option>
                  ))}
                </Select>
              </Form.Item>

              <Form.Item noStyle shouldUpdate={(prevValues, currentValues) => prevValues.templateId !== currentValues.templateId}>
                {({ getFieldValue }) => {
                  const templateId = getFieldValue('templateId');
                  return templateId ? renderTemplateConfig(templateId) : null;
                }}
              </Form.Item>

              <div style={{ textAlign: 'right' }}>
                <Button type="primary" htmlType="submit" loading={loading}>
                  提交作业
                </Button>
              </div>
            </Space>
          </Form>
        </Card>

        <Card title="作业列表" style={{ marginTop: '24px' }}>
          <Table
            dataSource={jobs}
            columns={[
              { title: '作业名称', dataIndex: 'name', key: 'name' },
              { title: '作业类型', dataIndex: 'type', key: 'type', render: (type) => (
                <Tag color={type === 'training' ? 'blue' : 'green'}>
                  {type === 'training' ? '训练' : '评估'}
                </Tag>
              )},
              { 
                title: '状态', 
                dataIndex: 'status', 
                key: 'status', 
                render: (status) => (
                  <Space>
                    <Tag color={getStatusColor(status)}>{getStatusText(status)}</Tag>
                    {status === 'running' && <Progress percent={60} size="small" status="active" />}
                  </Space>
                )
              },
              { 
                title: '模型类型', 
                dataIndex: ['modelConfig', 'modelType'], 
                key: 'modelType' 
              },
              { 
                title: '创建时间', 
                dataIndex: 'createdAt', 
                key: 'createdAt',
                render: (time) => formatDateTime(time)
              },
              { 
                title: '操作', 
                key: 'action', 
                render: (_, record) => (
                  <Space>
                    {record.status === 'pending' && (
                      <Button type="link" icon={<PlayCircleOutlined />}>开始</Button>
                    )}
                    {record.status === 'running' && (
                      <Button type="link" danger icon={<StopOutlined />}>停止</Button>
                    )}
                    {record.status === 'completed' && record.metrics && (
                      <Button 
                        type="link" 
                        icon={<PlusOutlined />}
                        onClick={() => {
                          setCurrentJob(record);
                          setShowSaveModelModal(true);
                        }}
                      >保存模型</Button>
                    )}
                    <Button type="link" icon={<ReloadOutlined />} onClick={() => loadJobs()}>刷新</Button>
                  </Space>
                )
              }
            ]}
            rowKey="id"
            expandable={{
              expandedRowRender: renderJobDetails,
              rowExpandable: () => true,
            }}
          />
        </Card>
      </Content>

      {/* 结果展示模态框 */}
      <Modal
        title="作业结果详情"
        open={showResultsModal}
        onCancel={() => setShowResultsModal(false)}
        footer={[
          <Button key="back" onClick={() => setShowResultsModal(false)}>
            关闭
          </Button>,
          <Button 
            key="save" 
            type="primary" 
            onClick={() => {
              setShowResultsModal(false);
              setShowSaveModelModal(true);
            }}
          >
            保存为模型
          </Button>
        ]}
        width={800}
      >
        {currentJob && (
          <Space direction="vertical" style={{ width: '100%' }}>
            <Title level={5}>作业信息</Title>
            <div style={{ display: 'flex', gap: '20px' }}>
              <div>
                <Text strong>作业名称：</Text>
                <Text>{currentJob.name}</Text>
              </div>
              <div>
                <Text strong>模型类型：</Text>
                <Text>{currentJob.modelConfig.modelType}</Text>
              </div>
            </div>
            
            {currentJob.metrics && (
              <>
                <Divider>评估指标</Divider>
                <Row gutter={16}>
                  {Object.entries(currentJob.metrics).map(([key, value]) => (
                    <Col span={8} key={key}>
                      <Card>
                        <Statistic 
                          title={key} 
                          value={typeof value === 'number' ? value : 0}
                          precision={4}
                        />
                      </Card>
                    </Col>
                  ))}
                </Row>
                
                <Divider>性能可视化</Divider>
                <div 
                  ref={chartRef} 
                  style={{ width: '100%', height: '400px', marginTop: '20px' }}
                />
              </>
            )}
          </Space>
        )}
      </Modal>

      {/* 保存模型模态框 */}
      <Modal
        title="保存模型"
        open={showSaveModelModal}
        onCancel={() => setShowSaveModelModal(false)}
        footer={null}
        width={600}
      >
        <Form
          form={modelForm}
          layout="vertical"
          onFinish={handleSaveModel}
        >
          <Form.Item 
            name="name" 
            label="模型名称" 
            rules={[{ required: true, message: '请输入模型名称' }]}
            initialValue={currentJob?.name + '_model' || ''}
          >
            <Input placeholder="请输入模型名称" />
          </Form.Item>
          <Form.Item 
            name="version" 
            label="版本号"
            rules={[{ required: true, message: '请输入版本号' }]}
          >
            <Input placeholder="请输入版本号" type="number" min={1} />
          </Form.Item>
          <Form.Item 
            name="description" 
            label="模型描述"
          >
            <Input.TextArea rows={4} placeholder="请输入模型描述" />
          </Form.Item>
          <div style={{ textAlign: 'right' }}>
            <Button onClick={() => setShowSaveModelModal(false)} style={{ marginRight: '10px' }}>
              取消
            </Button>
            <Button type="primary" htmlType="submit" loading={loading}>
              保存模型
            </Button>
          </div>
        </Form>
      </Modal>
    </Layout>
  );
};

export default JobsPage;